﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using ExcelGenerator.SpreadSheet.Styles;

namespace ExcelGenerator.SpreadSheet
{
    public class Workbook
    {
        private StringBuilder sb;

        
        public List<Worksheet> Worksheets;
        
        public Workbook()
        {
            Worksheets = new List<Worksheet>();
            
            sb = new StringBuilder();
        }
        
        public void save(String file)
        {
            encodeWorksheets();

            TextWriter tw = new StreamWriter(file);
            tw.Write(sb.ToString());
            tw.Close();

        }

        public byte[] getBytes()
        {
            encodeWorksheets();

            return System.Text.Encoding.UTF8.GetBytes(sb.ToString());
        }

        private void encodeWorksheets(){

            sb.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?><?mso-application progid=\"Excel.Sheet\"?>");
            sb.Append("<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\" xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\" xmlns:html=\"http://www.w3.org/TR/REC-html40\">");

            sb.Append("<Styles>");
            foreach (KeyValuePair<string, Style> pair in StylesManager.getAllStyle())
            {
                String excelStyle = pair.Value.renderData();
                sb.Append(excelStyle);
            }
            sb.Append("</Styles>");

            foreach (Worksheet worksheet in Worksheets)
            {
                sb.Append("<Worksheet ss:Name=\"" + worksheet.title + "\">");
                sb.Append("<Table>");

                sb.Append(worksheet.encodeCells());

                sb.Append("</Table>");
                sb.Append("</Worksheet>");

            }

            sb.Append("</Workbook>");
        }

    }
}
